namespace SimpleWebServices.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Globalization;
    using System.Xml;
    using System.Xml.XPath;

    public sealed class DefaultConfiguration : IConfigurationSectionHandler
    {
        object IConfigurationSectionHandler.Create(object parent, object configContext, XmlNode section)
        {
            Dictionary<string, IXPathNavigable> result = new Dictionary<string, IXPathNavigable>();

            if (section != null)
            {
                XmlNodeList list = section.SelectNodes("/default/object");
                foreach (XmlNode node in list)
                {
                    Type type = Type.GetType(node.Attributes["type"].Value, true);
                    XmlAttribute attribute = node.Attributes["name"];
                    string name = (null == attribute) ? null as string : attribute.Value;
                    string key = string.IsNullOrEmpty(name)
                        ? type.FullName
                        : string.Format(CultureInfo.InvariantCulture, "{0} : {1}", type.FullName, name);
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(node.InnerXml);
                    result.Add(key, xml);
                }
            }

            return result;
        }
    }
}